<template>
  <div class="selector">
    <el-popover
      placement="bottom-start"
      trigger="hover"
      :popper-style="{ padding: 0 }"
      v-model:visible="visible"
    >
      <template #reference>
        <span class="u-reference">
          <span class="u-trigger">{{ selectedLabel }}</span>
          <el-icon
            v-show="selectedValue"
            class="u-icon-remove"
            @click.stop="clickClean"
          >
            <Close />
          </el-icon>
          <el-icon class="u-icon-arrow" :class="{ 'u-turn': visible }">
            <ArrowDown />
          </el-icon>
        </span>
      </template>

      <div class="selector-options">
        <div
          v-for="item in options"
          class="u-option"
          :class="{ 'u-actived': item.value === selectedValue }"
          :key="item.value"
          @click="() => clickOption(item)"
        >
          {{ item.label }}
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup name="Selector">
import { ref, computed } from 'vue'

const props = defineProps({
  // 默认值，父组件可通过v-model="xxx"绑定
  modelValue: [Number, String, Boolean],
  // 文案，表单项名字
  label: {
    type: String,
    default: '下拉选项',
  },
  // 下拉选项
  options: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:modelValue', 'change'])

const visible = ref(false)
// 当前选中项的value
const selectedValue = ref(props.modelValue)

// 当前选中项的label
const selectedLabel = computed(() => {
  const selectedItem = props.options.find(
    (item) => item.value === props.modelValue
  )
  return selectedItem?.label ?? props.label
})

// 点击选项
function clickOption(item) {
  selectedValue.value = item.value
  visible.value = false
  emit('update:modelValue', item.value)
  emit('change', item.value)
}

// 点击清空
function clickClean() {
  clickOption({
    label: null,
    value: null,
  })
}
</script>

<style lang="scss" scoped>
.selector {
  .u-reference {
    display: inline-flex;
    align-items: center;
    padding: 0 8px;
    line-height: 22px;
    font-size: 14px;
    border-radius: 2px;
    background-color: rgba(59, 104, 240, 0.1);
    color: #3b68f0;
    cursor: pointer;
    .u-icon-remove {
      margin-left: 8px;
    }
    .u-icon-arrow {
      margin-left: 8px;
      transition: all 0.2s;
      &.u-turn {
        transform: rotate(180deg);
      }
    }
  }
}
.selector-options {
  margin: 6px 0;
  .u-option {
    padding: 0 32px 0 20px;
    color: var(--el-text-color-regular);
    height: 34px;
    line-height: 34px;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    &:hover {
      background-color: var(--el-fill-color-light);
    }
    &.u-actived {
      color: var(--el-color-primary);
    }
  }
}
</style>
